package com.eternal.framework.utils;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;

/**
 * Created by goldze on 2017/5/14.
 * 常用工具类
 */
public final class Utils {

    @SuppressLint("StaticFieldLeak")
    private static Context context;
    private static Application application;

    private Utils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 初始化工具类
     *
     * @param application app
     */
    public static void init(@NonNull final Application application) {
        Utils.application=application;
        Utils.context = application.getApplicationContext();
    }

    /**
     * 获取ApplicationContext
     *
     * @return ApplicationContext
     */
    public static Context getContext() {
        if (context != null) {
            return context;
        }
        throw new NullPointerException("should be initialized in application");
    }

    public static boolean isMainThread(){
        return Looper.myLooper()==Looper.getMainLooper();
    }

    public static Application getApp(){
        if(application!=null){
            return application;
        }
        throw new NullPointerException("should be initialized in application");
    }

    public static String getString(@StringRes int res){
        return application.getString(res);
    }

    public static String getString(@StringRes int res, Object... params){
        return application.getString(res, params);
    }

    public static ComponentName startService(Intent intent){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return application.startForegroundService(intent);
        }
        return application.startService(intent);
    }
}